/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.amuthu.expression.function.indicator;

import org.amuthu.DataStore;
import org.amuthu.expression.Expression;
import org.amuthu.expression.exception.InvalidArgumentException;
import org.amuthu.expression.terminal.QuoteExprType;
import org.amuthu.expression.terminal.QuoteExpression;
import org.amuthu.parser.ExpressionVisitor;

/**
 * lag(quote, startOffset)
 * @author prabhu
 */
public class LagFunction extends AbstractFunctionEvaluator
{
   public LagFunction()
   {
   }

   @Override
   public double computeIndicator(DataStore dataStore, Expression[] arguments, ExpressionVisitor visitor) throws InvalidArgumentException
   {
      if (arguments.length < 2)
      {
         throw new InvalidArgumentException("LAG function zero args");
      }

      QuoteExprType quoteType = ((QuoteExpression) arguments[0]).getQuoteKind();

      int lag = (int) visitor.evaluate(arguments[1]);

      if (lag < 0)
      {
         throw new InvalidArgumentException("LAG function zero args");
      }

      double result = 0.0;

      switch (quoteType)
      {
         case DAY_CLOSE:
            result = dataStore.getClose()[dataStore.getSize() - 1 - lag];
            break;

         case DAY_OPEN:
            result = dataStore.getOpen()[dataStore.getSize() - 1 - lag];
            break;

         case DAY_HIGH:
            result = dataStore.getHigh()[dataStore.getSize() - 1 - lag];
            break;

         case DAY_LOW:
            result = dataStore.getLow()[dataStore.getSize() - 1 - lag];
            break;

         case DAY_VOLUME:
            result = dataStore.getVolume()[dataStore.getSize() - 1 - lag];
            break;

         default:
            throw new AssertionError();
      }

      return result;
   }

   public int computeDayDependency(DataStore dataStore, Expression[] arguments, ExpressionVisitor visitor) throws InvalidArgumentException
   {
      if (arguments.length < 2)
      {
         throw new InvalidArgumentException("LAG function zero args");
      }

      return  (int) visitor.evaluate(arguments[1]);
   }

   @Override
   public boolean updateParameters(DataStore dataStore, Expression[] arguments, ExpressionVisitor visitor)
   {
      throw new UnsupportedOperationException("Not supported yet.");
   }
}
